﻿Imports System.ServiceModel.DomainServices.Client
Imports LullabyFullDeCaixa.Web
Imports System.Collections.ObjectModel

Partial Public Class DetallGestioNeteja
    Inherits ChildWindow

#Region "Crear i Destruir"
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub DetallGestioHostals_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            Me.Activity.IsActive = True

            AddHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
            Contexte.LoadHostals()
            AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
            Contexte.LoadUsuaris()

            Me.grdNeteges.ItemsSource = DadesBuscador
        End If
    End Sub
#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() Then
                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
                Activity.IsActive = True
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.ErrorGuardantDades)
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region

#Region "Carregar Dades"
    Private _HostalsCarregats As Boolean = False
    Private _UsuarisCarregats As Boolean = False

    Public Sub HostalsCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
        _HostalsCarregats = True

        If _HostalsCarregats And _UsuarisCarregats Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub

    Public Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
        _UsuarisCarregats = True

        If _HostalsCarregats And _UsuarisCarregats Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub

#End Region

#Region "Buscador"

    Private DadesBuscador As ObservableCollection(Of Neteja) = New ObservableCollection(Of Neteja)

    Private Sub Buscador_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        BuscaNeteges(True)
    End Sub

    Private Sub OmpleDadesBuscador()
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim LListaHostals As List(Of Hostal) = Contexte.Hostals.ToList
            LListaHostals.Insert(0, New Hostal() With {.Id = -1, .Nom = ""})
            Me.cboHostals.ItemsSource = LListaHostals

            Dim LListaUsuaris As List(Of Usuari) = (From U As LullabyFullDeCaixa.Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari <> EnumTipusUsuari.Neteja).ToList
            LListaUsuaris.Insert(0, New Usuari() With {.Id = -1, .Nom = ""})
            Me.cboUsuaris.ItemsSource = LListaUsuaris
        Else
            Me.cboHostals.ItemsSource = Contexte.HostalsPerUsuariActual

            Dim LListaHostalsAssignats As List(Of Web.Hostal) = (From UH As Web.UsuariHostal In Contexte.UsuariActual.UsuariHostals Select UH.Hostal).ToList
            Dim LListaUsuaris As List(Of Usuari) = (From UH As Web.UsuariHostal In Contexte.DomainContext.UsuariHostals Where LListaHostalsAssignats.Contains(UH.Hostal) And UH.Usuari.IdTipusUsuari <> EnumTipusUsuari.Neteja Select UH.Usuari).ToList
            LListaUsuaris.AddRange((From U As Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari = EnumTipusUsuari.Administrador))
            LListaUsuaris.Insert(0, New Usuari() With {.Id = -1, .Nom = ""})
            Me.cboUsuaris.ItemsSource = LListaUsuaris
        End If

        Me.cboHostals.SelectedItem = cboHostals.Items(0)
        Me.cboUsuaris.SelectedItem = cboUsuaris.Items(0)
        Me.dtpDataInicial.SelectedDate = Today.AddDays(-7).ToShortDateString
        Me.dtpDataFinal.SelectedDate = Today.ToShortDateString

        BuscaNeteges(True)
    End Sub

    Private Sub BuscaNeteges(MostrarBarraProgrés As Boolean)
        Me.Activity.IsActive = MostrarBarraProgrés

        Dim DataInicial As Date?
        Dim DataFinal As Date?

        DataInicial = Me.dtpDataInicial.SelectedDate
        If DataInicial.HasValue Then DataInicial = Date.SpecifyKind(DataInicial.Value.Date, DateTimeKind.Utc)

        DataFinal = Me.dtpDataFinal.SelectedDate
        If DataFinal.HasValue Then DataFinal = Date.SpecifyKind(DataFinal.Value.Date, DateTimeKind.Utc)

        Dim Hostals As List(Of Integer) = New List(Of Integer)
        Hostals.Add(DirectCast(Me.cboHostals.SelectedItem, Hostal).Id)

        LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetNetegesPerHostalUsuariIDatesQuery(Hostals, DirectCast(Me.cboUsuaris.SelectedValue, Usuari).Id, DataInicial, DataFinal), _
           New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.Neteja))(AddressOf NetegesLoaded), _
           Nothing)
    End Sub

    Private Sub NetegesLoaded(ByVal Neteges As LoadOperation(Of LullabyFullDeCaixa.Web.Neteja))
        'Un cop carregat ho guardem en una llista
        Me.Activity.IsActive = False

        'Afegim els nous
        For Each Neteja As Neteja In (From N As Neteja In Neteges.Entities Order By N.Data Descending, N.IdHostal).ToList()
            If Not DadesBuscador.Contains(Neteja) Then DadesBuscador.Insert(0, Neteja)
        Next

        'Traiem els vells
        Dim NetegesATreure As List(Of Neteja) = New List(Of Neteja)
        For Each Neteja As Neteja In DadesBuscador
            If Not Neteges.Entities.Contains(Neteja) Then NetegesATreure.Add(Neteja)
        Next

        For Each Neteja As Neteja In NetegesATreure
            DadesBuscador.Remove(Neteja)
        Next

    End Sub
#End Region

#Region "Boto Eliminar i afegir"

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim Neteja As Neteja = DirectCast(grdNeteges.SelectedItem, Neteja)

        LullabyFullDeCaixa.Contexte.DomainContext.Netejas.Remove(Neteja)

        DadesBuscador.Remove(Neteja)
    End Sub

    Private Sub btnAfegir_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim novaNeteja As New LullabyFullDeCaixa.Web.Neteja() With {.Data = Date.SpecifyKind(Now.Date, Global.System.DateTimeKind.Utc), .HoraObertura = Now.TimeOfDay, .IdUsuariObertura = Contexte.UsuariActual.Id}
        Contexte.DomainContext.Netejas.Add(novaNeteja)


        Dim Child As NetejaAltaModificacio = New NetejaAltaModificacio(NetejaAltaModificacio.EnumMode.ModeAlta, novaNeteja)
        AddHandler Child.Closed, AddressOf Child_Tancat

        Child.Show()
    End Sub

    Private Sub btnTancar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Neteja As Neteja = grdNeteges.SelectedItem

        Neteja.UsuariFinalitzador = Contexte.UsuariActual
        Neteja.HoraTancament = Now.TimeOfDay

        Dim Child As NetejaAltaModificacio = New NetejaAltaModificacio(NetejaAltaModificacio.EnumMode.ModeTancament, Neteja)
        Child.Show()
    End Sub

    Private Sub btnEditar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Neteja As Neteja = grdNeteges.SelectedItem

        Dim Child As NetejaAltaModificacio = New NetejaAltaModificacio(NetejaAltaModificacio.EnumMode.ModeModificacio, Neteja)
        Child.Show()
    End Sub

    Private Sub Child_Tancat(Sender As Object, e As System.EventArgs)
        Dim Child As NetejaAltaModificacio = DirectCast(Sender, NetejaAltaModificacio)
        RemoveHandler Child.Closed, AddressOf Child_Closed

        If Child.DialogResult And Child.Mode = NetejaAltaModificacio.EnumMode.ModeAlta Then
            DadesBuscador.Insert(0, Child.Neteja)
            grdNeteges.SelectedItem = Child.Neteja
        End If
    End Sub

#End Region

    Private Sub grdNeteges_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdNeteges.SelectionChanged
        If e.AddedItems.Count = 0 Then
            Me.gridDetall.Visibility = Windows.Visibility.Collapsed
            Me.btnEliminar.IsEnabled = False
            Me.btnEditar.IsEnabled = False
            Me.btnTancar.IsEnabled = False
        Else
            Dim Neteja As Neteja = DirectCast(e.AddedItems(0), Neteja)

            Me.gridDetall.Visibility = Windows.Visibility.Visible
            Me.btnEliminar.IsEnabled = (Not Neteja.EsTancat And Neteja.UsuariCreador Is Contexte.UsuariActual) OrElse Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador
            Me.btnEditar.IsEnabled = Not Neteja.EsTancat OrElse Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador
            Me.btnTancar.IsEnabled = Not Neteja.EsTancat
        End If
    End Sub

    Private Sub Scroll_SizeChanged(ByVal sender As System.Object, ByVal e As System.Windows.SizeChangedEventArgs)
        Me.Components.MaxHeight = Math.Max(Me.Scroll.ViewportHeight, Me.Components.MinHeight)
        Me.Components.MaxWidth = Math.Max(Me.Scroll.ViewportWidth, Me.Components.MinWidth)
    End Sub

End Class

